package cn.fch.gotrip.service.impl;

import cn.fch.gotrip.api.BeanResponse;
import cn.fch.gotrip.dao.AdminDao;
import cn.fch.gotrip.entity.Admin;
import cn.fch.gotrip.service.AdminService;
import cn.fch.gotrip.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

/**
 * @program: gotrip
 * @description:
 * @CreatedBy: fch
 * @create: 2023-01-14 17:08
 **/
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminDao adminDao;

    @Autowired
    JwtUtil jwtUtil;

    @Override
    public BeanResponse login(Admin admin, HttpServletResponse response) {
        Admin dbAdmin = adminDao.findAdminByName(admin.getUsername());
        if (null == dbAdmin)
            return BeanResponse.unauthorized("账号不存在");
        BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
        if (bpe.matches(admin.getPassword(), dbAdmin.getPassword())) {
            dbAdmin.setPassword("");
            response.addHeader("Access-Control-Expose-Headers", "token");
            response.setHeader("token",
                    jwtUtil.generatorToken(dbAdmin.getUsername(), dbAdmin.getRole(), dbAdmin.getAvatar()));
            return BeanResponse.ok(dbAdmin);
        } else {
            return BeanResponse.unauthorized("账号密码错误");
        }
    }

    @Override
    public BeanResponse getAdminInfoByToken(String token) {
        Admin admin = jwtUtil.getAdminInfo(jwtUtil.getClaimsFromToken(token));
        if (null == admin) {
            return BeanResponse.unauthorized("token认证失败");
        }
        return BeanResponse.ok(admin);
    }

    @Override
    public Admin findAdminByName(Admin admin) {
        return adminDao.findAdminByName(admin.getUsername());
    }

}
